/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package uia.is202.survey;

import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.NotSupportedException;
import javax.transaction.UserTransaction;

/**
 *
 * @author n_aud5
 */
public class Respond extends HttpServlet {

    @PersistenceUnit
    protected EntityManagerFactory emf;

    // We are going to change data, so we need a transaction
    @Resource
    UserTransaction tx;

    /**
     * Handle get requests by calling processRequest()
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException
     * @throws ServletException
     */
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        processRequest(req, resp);
    }


    /**
     * Handle post requests by calling processRequest()
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException
     * @throws ServletException
     */
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        processRequest(req, resp);
    }


    /**
     * Handle requests. Sends a html page containing the department list.
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException
     * @throws ServletException
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String alder = request.getParameter("alder");
        String postnr = request.getParameter("postnr");

        try {
            tx.begin();
            EntityManager em = emf.createEntityManager();
            Response r = new Response(alder, postnr);
            em.persist(r);
            tx.commit();
        }
        catch(Exception e) {
            throw new ServletException("Transaction failed!", e);
        }


        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache");
        response.setHeader("Expires", "0");

        out.println("<html><head><title>Survey</title></head><body>");
        out.println("<h1>Thank you</h1>");
        out.println("<p>Your response was</p>");
        out.println("<p>Alder: "+alder+"</p>");
        out.println("<p>Postnr: "+postnr+"</p>");
        out.println("</body></html>");

    }


}
